import random

import time
from django import http
from django.shortcuts import render
# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from libs.captcha.captcha import captcha
from response_code import RET
from verifications import constants
from yuntongxun.sms import CCP
from tasks.sms import send_sms


class ImageCodeView(View):

    def get(self, request, uuid):
        # 生成图片验证码
        text, img = captcha.generate_captcha()
        # print(text)
        # print(img)
        # 保存图片验证码
        redis_conn = get_redis_connection('verify_code')
        red=redis_conn.setex('img_%s' % uuid, constants.IMAGE_CODE_EXPIRY, text)
        # 3, 返回图片给前端
        return http.HttpResponse(img, content_type='image/jpg')
class SMSCodeView(View):
    def get(self,request,mobile):
        uuid=request.GET.get('image_code_id')
        image_code_client = request.GET.get('image_code')
        # print(image_code_client)
        # print(uuid)

        if not all([uuid,image_code_client]):
            return http.JsonResponse({'code':RET.PARAMERR,'errmsg':'缺少必传参数'})
        redis_conn = get_redis_connection('verify_code')
        redis_image_code = redis_conn.get('img_%s'% uuid)

        if image_code_client is None:
            return http.JsonResponse({'code':RET.DATAERR,'errmsg':'验证码失效'})
        # 转小写后比较
        redis_image_code =redis_image_code.decode()
        if image_code_client.lower() != redis_image_code.lower():
            return http.JsonResponse({'code':RET.IMAGECODEERR,'errmsg':'验证码不正确'})
        # # 补充 判断是否发送中
        redis_sms_flag = redis_conn.get('sms_flag_%s' % mobile)
        if redis_sms_flag:
            # res={
            #     'code':0,
            #     'errmsg':'不能频繁请求短信'
            # }
            return http.JsonResponse({'code':RET.REQERR,'errmsg': '不能频繁请求短信'})
        sms_code ='%04d'%random.randint(0,9999)
        # redis_conn.setex('sms_%s' % mobile, SMS_CODE_EXPIRY, sms_code)
        # redis_conn.setex('sms_flag_%s'% mobile,SMS_CODE_REQ_LIMIT_TIME,'sending')
        pl=redis_conn.pipeline()
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_EXPIRY, sms_code)
        pl.setex('sms_flag_%s'% mobile,constants.SMS_CODE_REQ_LIMIT_TIME,'sending')
        pl.execute()
        #发送短信
        # CCP().send_template_sms(mobile,[sms_code,5],1)
        # 异步调用celery的发送短信任务
        send_sms.delay(mobile,sms_code,5,1)

        return http.JsonResponse({'code':RET.OK,'errmsg': 'success'})
